<?php
/**
 * User.class.php
 *
 * @author suning <snsnsky@gmail.com>
 * $Id$
 */

namespace controls\MobileApi\Center;

use Center\ActiveOffer;
use Center\CouponConfig;
use Center\QrCode;
use Center\Shop;
use Center\UserCoupon;
use MobileApi\ApiBase;
use Center\Active;
use Center\User as CUser;
use Common\PhotoImage;
use Geography\City;
use Safe\Filter;
use Mobile\AppPush;
use Notice\Sys;

/**
 * 用户 - 用户信息相关
 *
 * @package Center
 * @author  suning <snsnsky@gmail.com>
 * @since   1.0.0 2016-02-26
 */
class User extends ApiBase
{
    /**
     * 获取当前登录用户信息
     * <pre>
     * GET 无参数
     * </pre>
     *
     * @return string|void json
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {
     *         "UserId": 1, // 用户ID
     *         "UserNick": "", // 用户昵称, 未设置时为空
     *         "Gender": 2, // 性别 0 女, 1 男, 2 未设置
     *         "Birthday": "1986-08-10", // 生日
     *         "AvatarUrl": "http://img-head0.qbaobeiapp.com/01/00/1_100.jpg", // 头像地址
     *         "Sign": "", // 个性签名
     *         "CityId": 3401, // 城市ID
     *         "CityName": "长沙" // 所在地区
     *         "InviteUrl": "http://m.jinguonet.com/app/invite.php?uid=1" // 邀请链接
     *         "IsShop": 1, // 是否是商家 1：是 0：否
     *     }
     * }
     * 异常状态
     * 201: 用户不存在
     * </pre>
     */
    public function getUserInfo()
    {
        $uid = $this->isLogin(true);
        $userinfo = CUser::getInfoByIds($uid);

        if (empty($userinfo['UserId'])) {
            $this->output(201, '用户信息不存在');
        }

        $data = [
            'UserId' => (int)$userinfo['UserId'],
            'UserNick' => empty($userinfo['UserNick']) ? '' : $userinfo['UserNick'],
            'Gender' => (int)$userinfo['Gender'],
            'Birthday' => empty($userinfo['Birthday']) ? '' : $userinfo['Birthday'],
            'AvatarUrl' => $userinfo['HeadUrl'],
            'CityId' => (int)$userinfo['CityId'],
            'CityName' => (string)$userinfo['CityName'],
            'RealName' => (string)$userinfo['RealName'],
            'IdCode' => (string)$userinfo['IdCode'],
            'Mobile' => (string)$userinfo['Mobile'],
            'InviteUrl' => 'http://m.jinguonet.com/app/help/share.php?uid=' . $uid,
            'IsShop' => (int)$userinfo['IsShop'],
            'ShopId' => (int)$userinfo['ShopId'],
        ];

        $this->output(200, $data);
    }

    /**
     * 修改用户昵称
     * <pre>
     * POST
     * name: 用户昵称
     * </pre>
     *
     * @return string|void json
     * <pre>
     * {
     *    "Status": 200,
     *    "Result": {}
     * }
     * 异常状态
     * 201: 昵称最多2-12个字
     * 202: 用户名包含非法关键词
     * </pre>
     */
    public function modifyUserNick()
    {
        $uid = $this->isLogin(true, false);

        $name = trim($_POST['name']);
        $len = mb_strlen($name);
        if ($len < 2 || $len > 12) {
            $this->output(201, '昵称最多2-12个字');
        }

        // 检查非法用户名
        if (Filter::fastCheck($name)) {
            $this->output(202, '昵称包含非法关键词');
        }

        CUser::update($uid, [
            'UserNick' => $name
        ]);

        $this->output();
    }

    /**
     * 修改所在城市
     * <pre>
     * POST
     * cityid: 城市ID
     * </pre>
     *
     * @return string|void json
     * <pre>
     * {
     *    "Status": 200,
     *    "Result": {}
     * }
     * 异常状态
     * 201: 城市ID不存在
     * 202: 修改失败, 请稍后再试
     * </pre>
     */
    public function modifyCity()
    {
        $uid = $this->isLogin(true);
        $cityid = (int)$_POST['cityid'];

        if (empty(City::getCityById($cityid))) {
            $this->output(201, '城市ID不存在');
        }

        $ret = CUser::update($uid, [
            'CityId' => $cityid
        ]);

        if ($ret) {
            $this->output();
        }
        $this->output(202, '修改失败, 请稍后再试');
    }

    /**
     * 上传头像, 至少180*180, 不大于2M (上传前将头像裁剪至 800 * X 分辨率, 90质量)
     * <pre>
     * POST
     *    avatar: 头像文件
     * </pre>
     *
     * @return string|void json
     * <pre>
     * {
     *    "Status": 200,
     *    "Result": {
     *        "AvatarUrl": "http://img-head0.qbaobeiapp.com/01/00/1_100.jpg?v=3" 新头像地址
     *    }
     * }
     * 异常状态
     * 201: 没有选择图片！
     * 202: 图片上传失败！
     * 203: 图片类型错误！
     * 204: 图片非法！
     * 205: 图片尺寸不可小于180*180像素
     * 206: 图片大小不能大于2M
     * 207: 图片超过服务器限制大小!
     * 208: 图片超过上传框限制大小!
     * 209: 找不到临时文件夹！
     * 210: 图片写入失败！
     * 211: 图片裁剪失败, 请稍后重试!
     * </pre>
     */
    public function uploadAvatar()
    {
        set_time_limit(65);
        $uid = $this->isLogin(true, false);

        $file = $_FILES['avatar'];

        $image_status = PhotoImage::checkImage($file, 180, 180, 2097152);

        if (!$image_status['status']) {
            $err_code = [
                205 => '图片尺寸不可小于180*180像素',
                206 => '图片大小不能大于2M'
            ];

            $code = intval('20' . $image_status['code']);
            if ($code == 2010) {
                $code = 210;
            }

            $this->output($code, isset($err_code[$code]) ? $err_code[$code] : $image_status['msg']);
        }
        $now = time();
        $ret = CUser::saveHeadUrl($uid, $image_status);

        if ($ret) {
            CUser::update($uid, ['HeadUrl' => $ret . '?v=' . $now]);
            $this->output(200, [
                'AvatarUrl' => $ret . '?v=' . $now
            ]);
        }

        $this->output(211, '图片裁剪失败, 请稍后重试!');
    }

    /**
     * 我的礼品
     * <pre>
     * GET
     *     offset: 可选， 偏移量 默认0
     *     limit:  可选， 每次数量, 最高不超过50 默认20
     * </pre>
     *
     * @return void|string 返回JSON数据
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {
     *         "Total": 21,
     *         "List": [
     *             {
     *                 "ActiveId": 1, // 活动id
     *                 "ActiveName": "活动名称最多显示", // 活动名称
     *                 "ActiveCover": "封面图地址" // 活动封面图地址
     *                 "Time" '2017-09-08', // 活动时间
     *             },...
     *         ]
     *     },
     *     "ServerTime": 1511665405
     * }
     * 异常状态：
     * </pre>
     */
    public function getPrizeList()
    {
        $uid = $this->isLogin(true);
        $offset = (int)$_GET['offset'];
        $limit = (int)$_GET['limit'];
        $offset = max(0, $offset);
        $limit = $limit < 1 ? 20 : min($limit, 50);
        $list_info = ActiveOffer::getMyGift($uid, $offset, $limit);
        $list = [];
        if (!empty($list_info['data'])) {
            $actives = Active::getInfoByIds($list_info['data']);
            foreach ($actives as $v) {
                $list[] = [
                    'ActiveId' => $v['Id'],
                    'ActiveName' => $v['Name'],
                    'ActiveCover' => $v['Cover'],
                    'Time' => $v['CreateTime'],
                ];
            }
        }
        $data = [
            'Total' => intval($list_info['count']),
            'List' => $list
        ];
        $this->output(200, $data);
    }

    /**
     * 我的会员二维码列表
     * <pre>
     * GET
     *     offset: 可选， 偏移量 默认0
     *     limit:  可选， 每次数量, 最高不超过50 默认20
     * </pre>
     *
     * @return void|string 返回JSON数据
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {
     *         "Total": 21,
     *         "List": [
     *             {
     *                 "CodeId": 1, // 二维码id
     *                 "ShopId": 1,
     *                 "ShopName": "名称最多显示",
     *                 "ShopCover": "封面图地址"
     *             },...
     *         ]
     *     },
     *     "ServerTime": 1511665655
     * }
     * 异常状态：
     * </pre>
     */
    public function getQrCodeList()
    {
        $uid = $this->isLogin(true);
        $offset = (int)$_GET['offset'];
        $limit = (int)$_GET['limit'];
        $offset = max(0, $offset);
        $limit = $limit < 1 ? 20 : min($limit, 50);
        $list_info = QrCode::getUserTypeCode($uid, QrCode::TYPE_SHOP_CHAP, $offset, $limit);
        $data = [
            'Total' => $list_info['count'],
            'List' => []
        ];
        if (!empty($list_info['data'])) {
            $codes = QrCode::getInfoByIds($list_info['data']);
            $sids = [];
            foreach ($codes as $v) {
                $sids[] = $v['TypeId'];
            }
            $shops = Shop::getInfoByIds($sids);
            foreach ($codes as $v) {
                if (!empty($shops[$v['TypeId']])) {
                    $data['List'][] = [
                        'CodeId' => $v['Id'],
                        'ShopId' => $v['TypeId'],
                        'ShopName' => $shops[$v['TypeId']]['Name'],
                        'ShopCover' => $shops[$v['TypeId']]['Cover'],
                    ];
                }
            }
        }

        $this->output(200, $data);
    }

    /**
     * 我的会员二维码详细
     * <pre>
     * GET
     *     codeid: 必选， 会员二维码id
     * </pre>
     *
     * @return void|string 返回JSON数据
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {
     *         "QrCodeUrl": "二维码地址",
     *         "ShopName": "店铺名",
     *         "Address": "店铺地址",
     *         "Mobile": "联系电话",
     *         "Abscissa": "坐标经度",
     *         "Ordinate": "坐标纬度",
     *     },
     *     "ServerTime": 1511665913
     * }
     * 异常状态：
     * </pre>
     */
    public function getQrCodeInfo()
    {
        $id = intval($_GET['codeid']);
        $qr_code = QrCode::getInfoByIds($id);
        if (empty($qr_code)) {
            $this->output(201, '参数错误');
        }
        $shop = Shop::getInfoByIds($qr_code['TypeId']);
        $data = [
            'QrCodeUrl' => 'gold://app/vip?id=' . $id,
            'ShopName' => $shop['Name'],
            'Address' => $shop['Address'],
            'Mobile' => $shop['Mobile'],
            'Abscissa' => $shop['Abscissa'],
            'Ordinate' => $shop['Ordinate'],
        ];
        $this->output(200, $data);
    }

    /**
     * 我的电子券列表
     * <pre>
     * GET
     *     type: 可选, 电子券状态 0：全部 1：有效 2：过期或已使用 默认0
     *     offset: 可选， 偏移量 默认0
     *     limit:  可选， 每次数量, 最高不超过50 默认20
     * </pre>
     *
     * @return void|string 返回JSON数据
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {
     *         "Total": 11,
     *         "List": [
     *             {
     *                 "CouponId": 1,
     *                 "CouponName": "电子券名称",
     *                 "Status": 1, // 是否已使用 1：未使用 2：已使用
     *                 "CashNum": 500,  // 金额
     *                 "Num": 5,  // 张数
     *                 "StartTime"： '有效期开始时间',
     *                 "EndTime"： '有效期结束时间',
     *                 "ValidText": "2017.12.1-2018.2.1期间使用", // 文案
     *                 "IsValid": 0 // 是否在有效期 0：否 1：是
     *             },...
     *         ]
     *     },
     *     "ServerTime": 1513694305
     * }
     * 异常状态：
     * </pre>
     */
    public function getMyCoupon()
    {
        $uid = $this->isLogin(true);
        $type = intval($_GET['type']);
        $offset = (int)$_GET['offset'];
        $limit = (int)$_GET['limit'];
        $offset = max(0, $offset);
        $limit = $limit < 1 ? 20 : min($limit, 50);
        $list_info = UserCoupon::getUserList($uid, 0, $type, 0, $offset, $limit);
        $data['Total'] = $list_info['count'];
        $list = [];
        if (!empty($list_info['data'])) {
            $ids = [];
            foreach ($list_info['data'] as $v) {
                $ids[$v['CouponId']] = $v['CouponId'];
            }
            $coupons = CouponConfig::getInfoByIds($ids);
            foreach ($list_info['data'] as $v) {
                $list[] = [
                    'CouponId' => $v['Id'],
                    'CouponName' => (string)$coupons[$v['CouponId']]['Name'],
                    'Status' => (int)$v['Status'],
                    'CashNum' => (string)$coupons[$v['CouponId']]['Value'],
                    'Num' => (int)$v['Amount'],
                    'StartTime' => $v['StartTime'],
                    'EndTime' => $v['EndTime'],
                    'ValidText' => date('Y.m.d', strtotime($v['StartTime'])) . '-' . date('Y.m.d', strtotime($v['EndTime'])) . '期间使用',
                    'IsValid' => $v['UpdateTime'] > date('Y-m-d H:i:s') ? 1 : 0,
                ];
            }
        }
        $data['List'] = $list;

        $this->output(200, $data);
    }

    /**
     * 电子券详细
     * <pre>
     * GET
     *     couponid: 必选, 电子券id
     * </pre>
     *
     * @return void|string 返回JSON数据
     * <pre>
     * {
     *     "Status": 200,
     *     "Result": {
     *         "CouponId": 1,
     *         "CouponName": "电子券名称",
     *         "Status": 0, // 是否已使用 0：否 1：是
     *         "CashNum": 500, // 金额
     *         "StartTime"： '有效期开始时间',
     *         "EndTime"： '有效期结束时间',
     *         "ValidText": "2017.12.1-2018.2.1期间使用",
     *         "QrCodeUrl": "http://sss.pne",
     *         "Desc": "1、消费5000方可使用\n2、每次最多使用2张\n3、仅限特定商户使用",
     *         "ShopName": "海尔电器",
     *         "ShopMobile": "0732-23209302",
     *         "ShopAddress": "醴陵市＊＊街＊＊号"
     *     },
     *     "ServerTime": 1514215531
     * }
     * 异常状态：
     * </pre>
     */
    public function getCouponInfo()
    {
        $uid = $this->isLogin(true);
        $id = intval($_GET['couponid']);
        $my_coupon = UserCoupon::getInfoByIds($id);
        if (empty($my_coupon) || $uid != $my_coupon['UserId']) {
            $this->output(201, '参数错误');
        }
        $coupon = CouponConfig::getInfoByIds($my_coupon['CouponId']);
        $shop = Shop::getInfoByIds($coupon['ShopId']);
        $code_info = QrCode::checkUserTypeCode($uid, QrCode::TYPE_SHOP_CHAP, $coupon['ShopId']);
        $data = [
            'CouponId' => $id,
            'CouponName' => trim($coupon['Name']),
            'Status' => (int)$my_coupon['Status'],
            'CashNum' => (int)$coupon['Value'],
            'StartTime' => trim($my_coupon['StartTime']),
            'EndTime' => trim($my_coupon['EndTime']),
            'ValidText' => date('Y.m.d', strtotime($my_coupon['StartTime'])) . '-' . date('Y.m.d', strtotime($my_coupon['EndTime'])) . '期间使用',
            'QrCodeUrl' => 'gold://app/ticket?id=' . (int)$code_info['Id'], // TODO
            'Desc' => trim($coupon['Desc']),
            'ShopName' => trim($shop['Name']),
            'ShopMobile' => trim($shop['Mobile']),
            'ShopAddress' => trim($shop['Address']),
        ];

        $this->output(200, $data);
    }
}
